package com.tistory.wonsama.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;

/**
 * WRITE LOG ON FILE 
 * @author wonsama
 * @since 2011.12.28
 */
public class WLog {

	private static final String DEFAULT_LOG_PATH = "resource/wlog.properties";
	
	private static final String KEY_LOG_DIR = "LOG_DIR";
	private static final String KEY_FILE_NAME = "LOG_FILE_NAME";
	private static final String KEY_LOG_ON = "LOG_ON";
	
	private static final String OFF = "OFF";
	private static final String SCREEN = "SCREEN";
	private static final String FILE = "FILE";
	
	private static final String SDF_DATE = "yyyyMMdd";
	private static final String SDF_TIME = "HH:mm:ss:SSS";
	
	private static final String LOG_SUFFIX = ".log";
	
	private static String LOG_DIR = null;
	private static String LOG_FILE_NAME = null;
	private static String LOG_ON = OFF;
	
	/**
	 * INIT
	 */
	static{
		
		Properties p = WProperties.loadProperties( DEFAULT_LOG_PATH );
		LOG_DIR = p.getProperty( KEY_LOG_DIR );
		LOG_FILE_NAME = p.getProperty( KEY_FILE_NAME );
		LOG_ON = p.getProperty( KEY_LOG_ON );
		
		//MAKE DIR
		WFile.mkDir(LOG_DIR);
	}
	
	
	
	/**
	 * INSERT SPACE
	 */
	public static void debugLine() {
		debug("________________________________________________________________\n", false);
	}
	
	/**
	 * WRITE LOG 
	 * @param message LOG MESSAGE
	 * @since 2011.12.28
	 */
	public static void debug(String message)
	{
		debug(message, true);
	}
			
	/**
	 * WRITE LOG 
	 * @param message LOG MESSAGE
	 * @param insertTime TIME
	 * @since 2011.12.28
	 */
	public static void debug(String message, boolean insertTime) {
		
		message = " " + message;
		
		//CHECK WRITE MODE
		if(LOG_ON.equals(OFF)){
			return;
		}
		
		if(LOG_ON.indexOf(SCREEN)>=0){
			
			StringBuffer sb = new StringBuffer();
			SimpleDateFormat sdfLog = new SimpleDateFormat( SDF_TIME , Locale.KOREA );
			if(insertTime){
				sb.append( "[" + sdfLog.format(new Date()) + "]" );
			}	
			sb.append( message );
			
			System.out.println( sb.toString() );
		}
		
		if(LOG_ON.indexOf(FILE)>=0){
			//WRITE
			PrintWriter pw = null;
			try {
				
				SimpleDateFormat sdfFile = new SimpleDateFormat( SDF_DATE , Locale.KOREA ); 
				Date date = new Date();
				String file = LOG_DIR + LOG_FILE_NAME + sdfFile.format(date) + LOG_SUFFIX;
				FileOutputStream fos = new FileOutputStream( file , true);
				pw = new PrintWriter( fos );
				
				StringBuffer sb = new StringBuffer();
				SimpleDateFormat sdfLog = new SimpleDateFormat( SDF_TIME , Locale.KOREA );
				if(insertTime){
					sb.append( "[" + sdfLog.format(new Date()) + "]" );	
				}
				sb.append( message );
				
				pw.println( sb.toString() );

			} catch (IOException ioe) {
			    ioe.printStackTrace();

			} finally {
				if (pw != null)
					pw.close();
			}
		}
		
	}//void debug
}
